using System.IO;
using System.Net;

namespace Youtube
{
    public class Worker
    {
        public bool CheckURL(string url)
        {
            string prefix   = "http://www.youtube.com";
            if (url.IndexOf(prefix) >= 0)
                return true;
            else 
                return false;
        }
        
        public string GetSource(string sourceURL)
        {
            string decollator   = "v=";
            if (sourceURL.IndexOf(decollator) < 0)
                return string.Empty;
            
            string video_id;
            if (sourceURL.IndexOf("&") >= 0)
            {
                string r        = sourceURL.Substring(sourceURL.IndexOf(decollator) + decollator.Length);
                video_id        = r.Substring(0, r.IndexOf("&"));;
            }
            else
                video_id        = sourceURL.Substring(sourceURL.IndexOf(decollator) + decollator.Length);
            if (video_id.Length == 0)
                return string.Empty;

            string pageContent  = getPage(sourceURL);
            decollator          = "&t=";
            string right        = pageContent.Substring(pageContent.IndexOf(decollator) + decollator.Length);
            string t            = right.Substring(0, right.IndexOf("&"));

            string result       = string.Format("http://www.youtube.com/get_video?video_id={0}&t={1}", video_id, t);
            return result;
        }
        
        private string getPage(string uri)
        {
            WebRequest request      = WebRequest.Create(uri);
            WebResponse response    = request.GetResponse();
            
            Stream dataStream       = response.GetResponseStream();
            StreamReader reader     = new StreamReader(dataStream);
            string responseFS       = reader.ReadToEnd();
            
            reader.Close();
            response.Close();
            
            return responseFS;
        }
    }
}
